/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gov.nist.ssd.swqb.core.files;

import gov.nist.ssd.swqb.core.ConfigFileManager;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Benjamin Herbomez
 */
public class RecentFileManager extends FileManager {

    protected static int maxFile = 15;
    protected LinkedList<String> recents = new LinkedList<String>();

    public RecentFileManager(ConfigFileManager fm) {
        super(fm);
        this.fileName = "recent";
        this.init();
    }

    private void init() {
        String fileDir = fm.getFileLocation(this.fileName, true);
        if (fileDir != null) {
            //Create the file
            this.fileLocation = fileDir;

            FileInputStream fsteam = null;
            try {
                fsteam = new FileInputStream(this.fileLocation);
                DataInputStream in = new DataInputStream(fsteam);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = br.readLine()) != null) {
                    this.recents.add(line);
                }
                while (this.recents.size() > maxFile) {
                    this.recents.pollLast();
                }
            } catch (IOException ex) {
                Logger.getLogger(PrefixManager.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    fsteam.close();
                } catch (IOException ex) {
                    Logger.getLogger(PrefixManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    @Override
    public void save() {
        String txt = "";
        for (String k : this.recents) {
            txt += k + "\n";
        }
        this.saveIntern(txt);
    }

    public void addFile(String dir) {
        //Replace on top
        if(this.recents.contains(dir))
            this.recents.remove(dir);
        this.recents.addFirst(dir);
        while (this.recents.size() > maxFile) {
            this.recents.pollLast();
        }
        this.save();
    }

    public List<String> getRecentFiles(){
        return this.recents;
    }
}
